import setting
import requests
from CommonModule import OperaMssql


def getDingToken():
    """
取钉钉TOKEN
    @return: 钉钉TOKEN
    """

    url = 'https://oapi.dingtalk.com/gettoken'
    params = {
        'appkey': setting.DINGTALK['AppKey'],
        'appsecret': setting.DINGTALK['AppSecret']
    }
    res = requests.get(url=url, params=params)

    if res.json()['errcode'] != 0:
        print(res.text)

    # print(res.json())
    # print('token:' + res.json()['access_token'])
    return res.json()['access_token']


def getDingDepartmentIdList(dingToken):
    """
取钉钉所有部门的ID并组成列表
    @param dingToken:
    @return:钉钉所有部门的ID组成的列表
    """
    url = 'https://oapi.dingtalk.com/department/list'
    params = {
        'access_token': dingToken,
        'fetch_child': True
    }
    res = requests.get(url=url, params=params)
    if res.json()['errcode'] != 0:
        print(res.text)
    return res.json()['department']


def updataDepartmentInfoSql(departmentList):
    """
更新数据库部门列表
    @param departmentList: 钉钉取回来的部门列表
    """
    ms = OperaMssql.MSSQL(host=setting.DB[setting.DB_CURRENT][0],
                          port=setting.DB[setting.DB_CURRENT][1],
                          user=setting.DB[setting.DB_CURRENT][2],
                          pwd=setting.DB[setting.DB_CURRENT][3],
                          db=setting.DB[setting.DB_CURRENT][4])

    # 设置所有状态为0
    strSql = 'UPDATE department_info set status=0'
    ms.ExecSql(strSql)

    strSql = "select * from department_info"

    resList = ms.ExecQuery(strSql)

    i = 1
    j = 0
    sqlList = []
    while (i < len(departmentList)):
        k = False
        while (j < len(resList)):
            if (int(resList[j][0]) == departmentList[i]['id']):
                k = True
                break
            j += 1
        if (k):
            strSql = "UPDATE department_info SET ding_upper_id = {0}, status = 1,name = '{1}' WHERE ding_id = {2}".format(
                departmentList[i]['parentid'], departmentList[i]['name'], departmentList[i]['id'])
        else:
            strSql = "insert into department_info (ding_id,ding_upper_id,name,status)values({0},{1},'{2}',1)".format(
                departmentList[i]['id'], departmentList[i]['parentid'], departmentList[i]['name'])

        i += 1
        j = 0
        sqlList.append(strSql)

    strSql = "UPDATE department_info SET ding_upper_id = 0, status = 1 ,name = '{0}' WHERE ding_id = 1".format(
        departmentList[0]['name'])
    sqlList.append(strSql)
    ms.ExecSqlList(sqlList)


def getDingUserInfoList(dingToken):
    """

    @param dingToken:
    @return: 取得钉钉上所有用户的信息列表
    """

    # 连接数据库
    ms = OperaMssql.MSSQL(host=setting.DB[setting.DB_CURRENT][0],
                          port=setting.DB[setting.DB_CURRENT][1],
                          user=setting.DB[setting.DB_CURRENT][2],
                          pwd=setting.DB[setting.DB_CURRENT][3],
                          db=setting.DB[setting.DB_CURRENT][4])
    # conn = ms.GetConnect()
    # print(conn)

    # 从数据库中取部门ID列表
    strSql = 'select ding_id FROM department_info WHERE status=1'

    dbDepartmentList = ms.ExecQuery(strSql)

    # 取ding上用户ID列表
    dingUserIdList = []
    url = 'https://oapi.dingtalk.com/user/getDeptMember'
    for deptId in dbDepartmentList:
        params = {
            'access_token': dingToken,
            'deptId': deptId
        }
        res2 = requests.get(url=url, params=params)
        setting.DingSleep()
        if res2.json()['errcode'] != 0:
            print(res2.text)
        dingUserIdList.extend(res2.json()['userIds'])

    # 删除列表中重复项
    dingUserIdList = list(dict.fromkeys(dingUserIdList))

    # 由用户dingId取用户信息
    dingUserInfoList = []

    url = 'https://oapi.dingtalk.com/user/get'
    for user_id in dingUserIdList:
        userInfo = []
        params = {
            'access_token': dingToken,
            'userid': user_id
        }
        res3 = requests.get(url=url, params=params)
        setting.DingSleep()
        if res3.json()['errcode'] != 0:
            print(res3.text)
        userInfo.append(res3.json()['userid'])
        temp1 = [str(temp) for temp in res3.json()['department']]
        tempDepartmentList = ",".join(temp1)
        userInfo.append(tempDepartmentList)
        userInfo.append(res3.json()['name'])
        dingUserInfoList.append(userInfo)
    return dingUserInfoList


# 对比后写入数据库
def updataDbUserInfoList(dingUserInfoList):
    """

    @param dingUserInfoList:
    """
    # 连接数据库
    ms = OperaMssql.MSSQL(host=setting.DB[setting.DB_CURRENT][0],
                          port=setting.DB[setting.DB_CURRENT][1],
                          user=setting.DB[setting.DB_CURRENT][2],
                          pwd=setting.DB[setting.DB_CURRENT][3],
                          db=setting.DB[setting.DB_CURRENT][4])
    # 设置所有人员状态为0
    strSql = 'UPDATE person_info set status=0'
    ms.ExecSql(strSql)

    # 取用户表中所有数据
    strSql = 'select ding_id from person_info'
    dbUserList = ms.ExecQuery(strSql)

    i = j = 0
    sqlList = []
    while (i < len(dingUserInfoList)):
        k = False
        while (j < len(dbUserList)):
            tempA = int(dbUserList[j][0])
            tempB = int(dingUserInfoList[i][0])
            if (tempA == tempB):
                k = True
                break
            j += 1

        if (k):
            strSql = "UPDATE person_info SET department_list_id = '{0}',name = '{1}', status = 1 WHERE ding_id = '{2}'".format(
                dingUserInfoList[i][1], dingUserInfoList[i][2], dingUserInfoList[i][0])
        else:
            strSql = "insert into person_info (ding_id,department_list_id,name,status)values('{0}','{1}','{2}',1)".format(
                dingUserInfoList[i][0], dingUserInfoList[i][1], dingUserInfoList[i][2])
        j = 0
        i += 1
        sqlList.append(strSql)
    # print(sqlList)

    return ms.ExecSqlList(sqlList)
